import React from 'react';
import {WeaDialog,WeaInput,WeaFormItem,WeaRightMenu,WeaLocaleProvider} from 'ecCom';
import {WeaForm, WeaSwitch} from 'comsMobx';
import {Button,message} from 'antd';
import { observable, action } from 'mobx';
import { observer} from 'mobx-react';

const getLabel = WeaLocaleProvider.getLabel;

class TemplateStore {
    @observable form = new WeaForm();

    @action initForm (conditions = []) {
        this.form = new WeaForm();
        this.form.setCondition(conditions);
    }

}

let templateStore = new TemplateStore();

@observer
export default class Main extends React.Component{

    constructor(props){
        super(props);
        const {length = 100} = props;

        this.state = {
            condition :  [
                {
                    "items": [
                        {
                            "colSpan": 2,
                            "conditionType": "INPUT",
                            'rules': `required|stringLength:${length}`,
                            "domkey": [
                                "name"
                            ],
                            "fieldcol": 12,
                            "isQuickSearch": true,
                            "label": getLabel(28050,'模板名称'),
                            "labelcol": 6,
                            "value": "",
                            "viewAttr": 3
                        }
                    ]
                }
            ],
            visible : false,
            date : '',
        }
    }

    // componentDidMount () {
    //     const {condition} = this.state;
        // const {form} = templateStore;
        // form.initFormFields(condition);
    // }

    // componentDidUpdate (preProps, preState) {
    //     const {visible,condition} = this.state;
        // if (visible) {
        //     const {form} = templateStore;
        //     form.initFormFields(condition);
        // }
    // }

    saveDate () {
        const { form } = templateStore;
        form.validateForm().then(f=>{
            if(f.isValid){
                // 验证通过
                const value = form.getFormParams();
                this.setState({visible : false});
                form.updateFields({
                    name: {
                        value: ''
                    }
                });
                typeof this.props.handleOk === 'function' && this.props.handleOk(value.name);
            }else{
                f.showErrors();
                this.setState({date: new Date()}); // 改变一个state的变量,强制页面刷新
            }
        });

    }

    handleCancel () {
        // const {form} = templateStore;
        // form.updateFields({
        //     name: {
        //         value: ''
        //     }
        // });
        this.setState({visible : false});
        typeof this.props.handleCancle === 'function' && this.props.handleCancle();

    }

    click (visible = true) {
        templateStore.initForm(this.state.condition);
        this.setState({visible:visible});
    }

    onChangeData(data) {

        const {length = 100} = this.props;
        const value = data.name.value;
        const { form } = templateStore;

        const charLength = value.replace(/[\u0391-\uFFE5]/g,"aaa").length;

        if(charLength > length) {

            // typeof this.props.lengthWarning === 'function' ? this.props.lengthWarning(length) : message.warning(`长度不能超过${length}个字符`)

            let endStr = '';

            for(let i = length; i > 0; i--) {

                endStr = value.substring(0,i);

                const charLength = endStr.replace(/[\u0391-\uFFE5]/g,"aaa").length;

                if(charLength <= length) {
                    break ;
                }
            }

            let timer = setTimeout(()=>{
                form.updateFields({
                    name:  endStr
                },false);
            },0)


            return ;
        }

        form.validateForm().then(f=>{
            if(f.isValid){
                // 验证通过, balabala业务代码
            }else{
                f.showErrors();
                this.setState({date: new Date()}); // 改变一个state的变量,强制页面刷新
            }
        });
    }

    dropMenuDatas () {

        const {modolName = getLabel(18418,'存为模板')} = this.props;

        let btns = {
            datas: [],
            collectParams: {
                favname: modolName,
                favouritetype: 2,
                objid: 0,
                importantlevel: 1,
            }
        };

        btns.datas.push({
            key: "1",
            disabled: false,
            icon: <i className='icon-coms-Preservation'/>,
            content: getLabel(86,'保存'),
            onClick: key => this.saveDate()
        })

        return btns;
    }

    render () {

        const {type = 'button',btnStyle = {},disabled = false,btnType = 'primary',btnSize = '',btnName = getLabel(18418,'存为模板'),modolName = getLabel(18418,'存为模板')} = this.props;

        const {condition,visible} = this.state;

        const { form } = templateStore;
        const formParams = form.getFormParams();
        const {isFormInit} = form;

        const footer = [
            <Button key="save" type="primary" onClick={() => this.saveDate()}>{getLabel(86,'保存')}</Button>,
        ];

        return (
            <div style={{display : 'inline-block'}}>
                {/*{*/}
                    {/*type === 'button' &&*/}
                    {/*<Button style={btnStyle} disabled={disabled} size={btnSize} type={btnType} onClick={()=>this.click(true)}>{btnName}</Button>*/}
                {/*}*/}
                <WeaDialog
                    className="wf-agent-saveAsModal"
                    title={modolName}
                    visible={visible}
                    icon="icon-coms-workflow"
                    iconBgcolor="#0079DE"
                    maskClosable={false}
                    buttons={footer}
                    onCancel={() => this.handleCancel()}
                    style={{width : '600px'}}
                    moreBtn={this.dropMenuDatas()}
                >
                    <WeaRightMenu
                        {...this.dropMenuDatas()}
                    >
                        {
                            isFormInit &&
                            <WeaFormItem
                                label={getLabel(28050,'模板名称')}
                                labelCol={{span:5,offset:3}}
                                wrapperCol={{span:13}}
                                error={form.getError(condition[0].items[0])}
                                tipPosition="bottom"
                                style={{padding : '60px 0'}}
                            >
                                <WeaSwitch fieldConfig={condition[0].items[0]}
                                           form={form} onChange={(data)=>this.onChangeData(data)}/>
                            </WeaFormItem>
                        }
                        {/*<div style={{padding:'35px'}}>*/}
                            {/*{*/}
                                {/*form.render({col: 1, showGroup: true}, {*/}
                                    {/*onChange: data => this.onChangeData(data),*/}
                                {/*})*/}
                            {/*}*/}
                        {/*</div>*/}

                    </WeaRightMenu>
                </WeaDialog>
            </div>
        )
    }
}